package com.ecp.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.StringWriter;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.dom4j.Document;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.ecp.commons.serialization.GenericBean;

public class Util {
	private static final OutputFormat	format	= OutputFormat.createPrettyPrint();

	public Util() {
	}
	
	/**
	 * 判断是否是汉字
	 * 
	 * @param s
	 * @return
	 * @author wangzheng
	 */
	public static boolean containsChinese(String s) {
		if (null == s || "".equals(s.trim()))
			return false;
		for (int i = 0; i < s.length(); i++) {
			if (isChinese(s.charAt(i)))
				return true;
		}
		return false;
	}

	public static boolean isChinese(char a) {
		int v = (int) a;
		return (v >= 19968 && v <= 171941);
	}

	public static String stringTabDecode(String s, String decodeSymbol) {
		if (s != null) {
			String s1 = s.replace(decodeSymbol, "\t");
			return s1.replace("\\" + "\t", decodeSymbol);
		} else {
			return "";
		}
	}

	public static String findSetter(Field field) {
		return "set"
				+ field.getName().replaceFirst(".",
						String.valueOf(field.getName().charAt(0)).toUpperCase());
	}

	public static String findGetter(Field field) {
		return "get"
				+ field.getName().replaceFirst(".",
						String.valueOf(field.getName().charAt(0)).toUpperCase());
	}

	/*
	 * parse string like 'a=1; b=2;'
	 */
	public static Map<String, String> parseNameValuePairs(String content, String delimiter) {
		Map<String, String> result = new HashMap<String, String>();

		if (content == null) {
			return result;
		}
		String NameValuePairs[] = content.split(delimiter);

		for (String str : NameValuePairs) {
			if (str != null) {
				String[] nv = str.split("=");
				if (nv.length != 2) {
					continue;
				}
				result.put(nv[0], nv[1]);
			}
		}
		return result;
	}

	public static int parseInt(String value) {
		int result = 0;
		try {
			result = Integer.parseInt(value);
		} catch (Exception e) {
		}
		return result;
	}

	public static String getJSONOutputString(HttpServletRequest request,
			HttpServletResponse response, JSONObject jobj) {
		boolean scriptTag = false;
		String cb = request.getParameter("callback");
		if (cb != null) {
			scriptTag = true;
			response.setContentType("text/javascript");
		} else {
			response.setContentType("application/x-json");
		}
		StringBuffer jsonbuffer = new StringBuffer();
		if (scriptTag) {
			jsonbuffer.append(cb + "(");
		}
		// response.getWriter().print(jsonData);
		jsonbuffer.append(jobj.toString());
		if (scriptTag) {
			jsonbuffer.append(");");
		}
		return jsonbuffer.toString();

	}

	public static String getJSONOutputString(HttpServletRequest request,
			HttpServletResponse response, JSONArray jobj) {
		boolean scriptTag = false;
		String cb = request.getParameter("callback");
		if (cb != null) {
			scriptTag = true;
			response.setContentType("text/javascript");
		} else {
			response.setContentType("application/x-json");
		}
		StringBuffer jsonbuffer = new StringBuffer();
		if (scriptTag) {
			jsonbuffer.append(cb + "(");
		}
		// response.getWriter().print(jsonData);
		jsonbuffer.append(jobj.toString());
		if (scriptTag) {
			jsonbuffer.append(");");
		}
		return jsonbuffer.toString();

	}

	/**
	 * 获取id串逗号的字符串 传入list 
	 **/

	public static String getIdString(List<Integer> list) {
		String ids = "";
		if (list != null && list.size() > 0) {
			for (Integer i : list) {
				ids += i + ",";
			}
		}
		if (!"".equals(ids) && ids.length() > 1) {
			ids = ids.substring(0, ids.length() - 1);
		}
		return ids;
	}

	/*
	 * list to string
	 * */
	public static <T> String ListToString(List<T> list, String sep) {
		StringBuffer sb = new StringBuffer();
		if (list != null && list.size() > 0 && sep != null) {
			for (T t : list) {
				sb.append(t).append(sep);
			}
			sb.setLength(sb.length() - sep.length()); // 去除最后多出来的分隔符
		}
		return sb.toString();
	}

	/*
		public static <T> JSONArray ListToJSONArray(List<T> list, String keys[]) {
			JSONArray jarr = new JSONArray();
			for (GenericBean obj : (List<GenericBean>)list) {
				jarr.put(obj.toJSON(keys));
			}
			return jarr;
		}
		*/
	/*
	@SuppressWarnings({ "unchecked", "rawtypes" })
	private static JSONArray ListToJSONArray(List list, String keys[]) {
		JSONArray jarr = new JSONArray();
		for (GenericBean obj : (List<GenericBean>) list) {
			jarr.put(obj.toJSON(keys));
		}
		return jarr;
	}
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public static List<String> ListToStringValueList(List list, String key) {
		List<String> valList = new LinkedList<String>();
		for (GenericBean obj : (List<GenericBean>) list) {
			valList.add(obj.getString(key));
		}
		return valList;
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	public static List<Integer> ListToIntValueList(List list, String key) {
		List<Integer> valList = new LinkedList<Integer>();
		for (GenericBean obj : (List<GenericBean>) list) {
			valList.add(obj.getInt(key));
		}
		return valList;
	}

	@SuppressWarnings("unchecked")
	public static JSONObject JSONObjectAppend(JSONObject dest, JSONObject src) {
		try {
			Iterator<String> iterator = src.keys();
			while (iterator.hasNext()) {
				String key = iterator.next();
				Object value;
				value = src.get(key);
				dest.put(key, value);
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return dest;
	}

	public static JSONObject requestToJSON(HttpServletRequest request) {
		return new JSONObject(request.getParameterMap()); // Map<String, String[]>
	}

	@SuppressWarnings("unchecked")
	public static Map<String, Object> jsonToMap(JSONObject jobj) {
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			Iterator<String> iterator = jobj.keys();
			while (iterator.hasNext()) {
				String key = iterator.next();
				map.put(key, jsonToObject(jobj.get(key)));
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return map;
	}

	public static List<Object> jsonArrayToList(JSONArray jarr) {
		List<Object> list = new LinkedList<Object>();
		try {
			for (int i = 0; i < jarr.length(); i++) {
				list.add(jsonToObject(jarr.get(i)));
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return list;
	}

	public static Object jsonToObject(Object obj) {
		if (obj instanceof JSONObject) {
			return jsonToMap((JSONObject) obj);
		} else if (obj instanceof JSONArray) {
			return jsonArrayToList((JSONArray) obj);
		} else {
			return obj;
		}
	}

	public static void main(String[] args) {
		try {

			String path = "E:/workspace/ECP/src/com/ecp/erp/bean/DeliveryDepartment.java";
			File file = new File(path);
			if (!file.exists() || file.isDirectory()) {
				System.out.println("不存在");
			} else {
				BufferedReader br = new BufferedReader(new FileReader(file));
				String temp = null;
				StringBuffer sb = new StringBuffer();
				temp = br.readLine();
				String s = "public void resetValues() {";
				while (temp != null) {
					sb.append(temp + " ");
					temp = br.readLine();
					if (temp != null && temp.contains("map.put")) {
						String regEx1 = "\"";
						Pattern p1 = Pattern.compile(regEx1);
						String[] r1 = p1.split(temp);
						if (r1.length > 2) {
							s += "\n" + "this.set(\"" + r1[1] + "\", \"\");";

							String s2 = r1[2].substring(36, r1[2].length());
							s2 = s2.substring(0, s2.indexOf(")"));

							String s3 = "";
							if (s2.equals("INTEGER")) {
								s3 = "public int get" + r1[1].substring(0, 1).toUpperCase()
										+ r1[1].substring(1, r1[1].length()) + "(){" + "\n"
										+ "return this.getInt(\"" + r1[1] + "\");" + "\n" + "}";
							}
							if (s2.equals("DOUBLE")) {
								s3 = "public double get" + r1[1].substring(0, 1).toUpperCase()
										+ r1[1].substring(1, r1[1].length()) + "(){" + "\n"
										+ "return this.getDouble(\"" + r1[1] + "\");" + "\n" + "}";
							}
							if (s2.equals("STRING")) {
								s3 = "public String get" + r1[1].substring(0, 1).toUpperCase()
										+ r1[1].substring(1, r1[1].length()) + "(){" + "\n"
										+ "return this.getString(\"" + r1[1] + "\");" + "\n" + "}";
							}
							if (s2.equals("BOOLEAN")) {
								s3 = "public boolean get" + r1[1].substring(0, 1).toUpperCase()
										+ r1[1].substring(1, r1[1].length()) + "(){" + "\n"
										+ "return this.getBoolean(\"" + r1[1] + "\");" + "\n" + "}";
							}
							if (s2.equals("DATETIME")) {
								s3 = "public DateTime get" + r1[1].substring(0, 1).toUpperCase()
										+ r1[1].substring(1, r1[1].length()) + "(){" + "\n"
										+ "return this.getDateTime(\"" + r1[1] + "\");" + "\n"
										+ "}";
							}
							System.out.println(s3);
						}
					}
				}
				s += "\n" + "}";
				System.out.println(s);
				br.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static boolean isIntNumb(String str) {
		return TextUtil.isIntNumb(str);
	}

	public static boolean isDoubleNumb(String str) {
		return TextUtil.isDoubleNumb(str);
	}

	public static boolean isFloatNumb(String str) {
		return TextUtil.isFloatNumb(str);
	}

	public static boolean isLetterOrNum(String str) {
		return TextUtil.isLetterOrNum(str);
	}

	public static java.sql.Timestamp getDateFormatByString(String argDate) throws Exception {
		return TextUtil.getDateFormatByString(argDate);
	}

	public static BigDecimal parseBigDecimal(String value) {
		BigDecimal result = null;
		try {
			result = new BigDecimal(value);
		} catch (Exception ex) {
			result = new BigDecimal(0);
		}
		return result;
	}

	public static String getMoneyString(long amount) {
		return TextUtil.getMoneyString(amount);
	}

	public static BigDecimal getItsPlus(BigDecimal bd) {
		BigDecimal zero = new BigDecimal(0);
		int amount = bd.compareTo(zero);
		if (amount < 0)
			return zero.subtract(bd);
		return bd;
	}

	/**
	 * 根据数值与精度位数返回相应精度位数的数值
	 * 
	 * @param amount
	 * @param presicion
	 * @return
	 */
	public static String getMoneyString(BigDecimal amount, int presicion) {
		if (amount == null) {
			return "0";
		}
		StringBuffer sb = new StringBuffer(presicion);
		if (presicion > 0) {
			sb.append("0.");
			for (int i = 0; i < presicion; i++) {
				sb.append("0");
			}
		} else {
			sb.append("0");
		}
		DecimalFormat fmt = new DecimalFormat(sb.toString());
		return fmt.format(amount);
	}

	public static String getSimpleDateFormatByTimestamps(java.sql.Timestamp argDate, String format) {
		String str = "";
		try {
			str = TextUtil.getSimpleDateFormatByTimestamps(argDate, format);
		} catch (Exception ex) {
		}
		return str;
	}

	public static String numberFormat(double number) {
		DecimalFormat format = new DecimalFormat("0.00");
		return format.format(number);
	}

	public static String formatXmlDocument(Document doc) {
		String str = "";
		XMLWriter xmlWriter = null;
		try {
			StringWriter writer = new StringWriter();
			xmlWriter = new XMLWriter(writer, format);
			xmlWriter.write(doc);
			str = writer.toString();
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		} finally {
			try {
				xmlWriter.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return str;
	}
	
	/*
	 * 截取字符串
	 */
	public static String cutStr(String orgStr,int length){
		return Util.cutStr(orgStr, length, "...");
	}
	
	public static String cutStr(String orgStr,int length,String zui){
		if(orgStr==null||orgStr.equals("")){
			return "";
		}
		if(orgStr.length()>length){
			orgStr = orgStr.substring(0, length)+zui;
		}
		return orgStr;
	}
}
